from mycelery.main import app
from celery.task import Task
import random,json  #生成随机验证码用模块
from django_redis import get_redis_connection  #redis模块
from ronglian_sms_sdk import SmsSDK  #云容联验证码模块
from renranapi.settings import constants #配置文件
import logging #日志模块
logger = logging.getLogger("django")   #选择日志记录方式
from django.conf import settings

# 监听整个任务的钩子
class Mytask(Task):
    def on_success(self, retval, task_id, args, kwargs):
        print('task success 11111')
        return super(Mytask, self).on_success(retval, task_id, args, kwargs)

    def on_failure(self, exc, task_id, args, kwargs, einfo):
        print('task failed')
        # 可以记录到程序中或者任务队列中,让celery尝试重新执行
        return super(Mytask, self).on_failure(exc, task_id, args, kwargs, einfo)

    def after_return(self, status, retval, task_id, args, kwargs, einfo):
        print('this is after return')
        return super(Mytask, self).after_return(status, retval, task_id, args, kwargs, einfo)

    def on_retry(self, exc, task_id, args, kwargs, einfo):
        print('this is retry')
        return super(Mytask,self).on_retry(exc, task_id, args, kwargs, einfo)

@app.task(name="send_sms",base = Mytask)
def send_sms(phone,sms_code):

    sdk = SmsSDK(settings.SMS["accId"], settings.SMS["accToken"], settings.SMS["appId"])
    # 短信内容
    data = (sms_code, constants.SMS_EXPIRT_TIME // 60)
    # 发送短信
    resp = sdk.sendMessage(settings.SMS["tid"], phone, data)

    resp = json.loads(resp)
    # 判断发送成功
    if resp.get("statusCode") != "000000":
        logger.error("发送短信失败!手机号:%s" % phone)
        raise Exception("发送短信失败")
    else:
        return {"detail": "短信已发送!请留意您的手机短信!"}
